package topt

import (
	"fmt"
	"go_auth/ext/settings"
	"go_auth/utils/commons"
	"go_auth/utils/redis"
	"math/rand"
	"os"
	"time"
)

func RandNewStr(length int) string {
	data := make([]byte, length)
	rand.Seed(time.Now().UnixNano())
	codes := settings.JwtBase.JwtSecret
	for i := 0; i < length; i++ {
		idx := rand.Intn(len(codes))
		data[i] = byte(codes[idx])
	}

	return string(data)
}

func CreateCode(userId string) bool {
	//连接redis服务端

	//fmt.Println(RandStringBytes(32))

	var secretId string
	secretId = RandNewStr(32)

	//判断issuer是否存在,不存在写入redis服务端
	keyId, err := redis.GetValue(userId, settings.RDb5)
	if !commons.CheckErr(err) {
		//不过期  这里加入错误异常  增加健壮性
		redis.SetStringValue(userId, secretId, -1, settings.RDb5)
	} else {

		//log 用户已经注册 密钥...
		fmt.Printf("%v 用户已经注册,秘钥 %v\n", os.Args[1], keyId)
		return false
	}

	//url := "otpauth://totp/xiaohan.com?secret=" + secretId + "&is_key=" + os.Args[1]
	//err = qrcode.WriteFile(url, qrcode.Medium, 256, userId+".png")
	//if !commons.CheckErr(err) {
	//	return false
	//}
	return true
}

func DeleteCode(userId string) {
	redis.Delete(userId, settings.RDb5)
}
